package com.lazyframework.security.web.authentication.provider;

import com.lazyframework.security.web.JwtClients;
import com.lazyframework.security.web.authentication.UserDetails;
import com.lazyframework.security.web.authentication.token.Authentication;
import com.lazyframework.security.web.authentication.token.JwtAuthenticationToken;
import com.lazyframework.security.web.exception.AuthenticationException;

/**
 * Create by lazy in 2019/11/7
 */
public class JwtAuthenticationProvider extends AbstractAuthenticationProvider {

    private JwtClients jwtClients;

    public void setJwtClients(JwtClients jwtClients) {
        this.jwtClients = jwtClients;
    }

    @Override
    public Authentication doAuthenticate(Authentication authentication) throws AuthenticationException {
        // Get user form request token.
        String userId = jwtClients.decode((String) authentication.principal());

        // Load UserDetails
        UserDetails userDetails = userDetailsService().loadById(userId);

        JwtAuthenticationToken result = new JwtAuthenticationToken(userDetails);
        result.setAuthenticated(true);

        return result;
    }

    @Override
    public boolean support(Class<?> auth) {
        return JwtAuthenticationToken.class.isAssignableFrom(auth);
    }

}
